package com.jiezhuo.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jiezhuo.cache.RedisCache;
import com.jiezhuo.entity.LoginUser;
import com.jiezhuo.entity.User;
import com.jiezhuo.entity.YourengConfig;
import com.jiezhuo.service.LoginService;
import com.jiezhuo.utils.JwtUtil;
import com.jiezhuo.utils.R;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private YourengConfig yourengConfig;

    @Override

    public R login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
//        if(Objects.isNull(authenticate)){
//            throw new RuntimeException("用户名或密码错误");
//        }
        //使用userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getUserid().toString();
        String userName = loginUser.getUser().getUserName();
        String jwt = JwtUtil.createJWT(userId);
        Map<String, Object> map = new HashMap<>();
        map.put("token",jwt);
        map.put("username",userName);
        //authenticate存入redis
        redisCache.setCacheObject("login:"+jwt,loginUser,120,TimeUnit.MINUTES);
        //把token响应给前端
        return R.ok().code(2000).data("data",map);
    }
    @Override
    public R logout(HttpServletRequest request) {
        String token = request.getHeader("token");
//      l
        redisCache.deleteObject("login:"+token);
        return R.ok().code(2000).msg("退出成功");
    }

    @Override
    public String getAccessToken() throws IOException {
        String accessToken = redisCache.getCacheObject("X-Access-Token");
        if(StringUtils.isEmpty(accessToken)){
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost post = new HttpPost("https://openapi.mp.usr.cn/usrCloud/user/getAuthToken");
            JSONObject json = new JSONObject();
            json.put("appKey",yourengConfig.getAppKey());
            json.put("appSecret",yourengConfig.getAppSecret());
            post.setEntity(new StringEntity(json.toString(),"UTF-8"));
            post.addHeader("Content-Type","application/json");
            HttpResponse httpResponse = httpclient.execute(post);
            // 获取结果实体
            HttpEntity entity = httpResponse.getEntity();
            JSONObject jsonObject=null;
            if (entity != null) {
                // 按指定编码转换结果实体为String类型
                String string = EntityUtils.toString(entity, HTTP.UTF_8);
                jsonObject = JSON.parseObject(string);

            }
            accessToken =jsonObject.getJSONObject("data").getString("X-Access-Token");
            redisCache.setCacheObject("X-Access-Token",accessToken, 90, TimeUnit.MINUTES);
        }
        return accessToken;
    }

    @Override
    public String getCommandAddress() {
//        String accessToken = redisCache.getCacheObject("CommandAddress");
//        if(StringUtils.isEmpty(accessToken)){
//            CloseableHttpClient httpclient = HttpClients.createDefault();
//            HttpPost post = new HttpPost("https://openapi.mp.usr.cn/usrCloud/user/getAuthToken");
//            JSONObject json = new JSONObject();
//            json.put("appKey",yourengConfig.getAppKey());
//            json.put("appSecret",yourengConfig.getAppSecret());
//            post.setEntity(new StringEntity(json.toString(),"UTF-8"));
//            post.addHeader("Content-Type","application/json");
//            HttpResponse httpResponse = httpclient.execute(post);
//            // 获取结果实体
//            HttpEntity entity = httpResponse.getEntity();
//            JSONObject jsonObject=null;
//            if (entity != null) {
//                // 按指定编码转换结果实体为String类型
//                String string = EntityUtils.toString(entity, HTTP.UTF_8);
//                jsonObject = JSON.parseObject(string);
//
//            }
//            accessToken =jsonObject.getJSONObject("data").getString("X-Access-Token");
//            redisCache.setCacheObject("X-Access-Token",accessToken, 90, TimeUnit.MINUTES);
//        }
//        return accessToken;
        return null;
    }


}
